<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <!--<el-form-item label="部门名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <!--<el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="部门状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>-->
      <!--<el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>-->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">刷新</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sysArea:area:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-upload" size="mini" @click="handleImport">导入</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button type="warning" icon="el-icon-refresh" size="mini" v-if="$store.getters.userinfo.userName == 'admin'"-->
<!--                   @click="updateSysAreaByJnfyRiskArea">1. 根据全国中高风险地区信息更新全国区划风险类型-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button type="warning" icon="el-icon-refresh" size="mini" v-if="$store.getters.userinfo.userName == 'admin'"-->
<!--                   @click="updateSysAreaCache">2. 重新生成全国区划缓存-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button type="warning" icon="el-icon-refresh" size="mini" v-if="$store.getters.userinfo.userName == 'admin'"-->
<!--                   @click="updateReturnInfoRiskByArea">3. 更新未核实人员风险类型-->
<!--        </el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="table"
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      lazy
      :load="load"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column  label="存货名称" width="460">
        <template slot-scope="scope">
            {{ scope.row.code ? '(' + scope.row.code  +')  ' +  scope.row.deptName : '' + scope.row.deptName  }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="code" label="编码" width="260"></el-table-column> -->
      <!--      <el-table-column prop="parentId" label="父部门id" width="260"></el-table-column>-->
      <!--      <el-table-column prop="ancestors" label="部门父级" width="260"></el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sysArea:area:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['sysArea:area:add']"
          >新增
          </el-button>
          <el-button
            v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sysArea:area:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="orderNum" label="排序" width="200"></el-table-column> -->


      <!--<el-table-column prop="riskflag" label="中高风险类型" width="200">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.riskTypeOption"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>-->
      <!--      <el-table-column prop="status" label="管控措施" :formatter="dealtypeFormat">-->

      <!--      </el-table-column>-->
      <!--<el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>-->
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="所属类别" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择所属类别"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存货名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入存货名称"/>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="简拼" prop="firstchar">
              <el-input v-model="form.firstchar" placeholder="请输入部门简拼"/>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" >
              <el-input v-model="form.phone" placeholder="请输入规格型号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格明细" >
              <el-input v-model="form.email" placeholder="请输入规格明细"/>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="数量" prop="counts">
              <el-input v-model="form.counts" placeholder="请输入数量"/>
            </el-form-item>
          </el-col> -->
         <!-- <el-col :span="12">
            <el-form-item label="吨位(重量)" >
              <el-input v-model="form.citycode" placeholder="请输入吨位(重量)"/>
            </el-form-item>
          </el-col>-->
          <el-col :span="12">
            <el-form-item label="单位" prop="dealtype">
              <el-input v-model="form.dealtype" placeholder="请输入单位"/>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="单价" prop="firstchar">
              <el-input v-model="form.firstchar" placeholder="请输入单价"/>
            </el-form-item>
          </el-col> -->


          <!-- <el-col :span="12">
            <el-form-item label="部门级别" prop="grade">
              <el-select v-model="form.grade" placeholder="部门级别" clearable size="small">
                <el-option
                  v-for="dict in levelOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col> -->

          <!--<el-col :span="12">
            <el-form-item label="是否质检" prop="riskflag">
              <el-select v-model="form.riskflag" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in dict.type.yes_no"
                    :key="dict.value" :label="dict.label" :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否自制" prop="ismain">
              <el-select v-model="form.ismain" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in dict.type.yes_no"
                    :key="dict.value" :label="dict.label" :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否在制" prop="iswork">
              <el-select v-model="form.iswork" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in dict.type.yes_no"
                    :key="dict.value" :label="dict.label" :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>-->
          <!-- <el-col :span="12">
            <el-form-item label="是否同步修改下级" prop="isDditSon">
              <el-select v-model="form.isDditSon" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in riskflagOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="备注信息" prop="remarks">
              <el-input v-model="form.remarks" placeholder="请输入备注信息"/>
            </el-form-item>
          </el-col>
          <!--<el-col :span="12">
            <el-form-item label="管控措施" prop="dealtype">
              <el-select v-model="form.dealtype" placeholder="请选择" clearable>
                <el-option
                  v-for="dict in dealtypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
              &lt;!&ndash;<el-radio-group v-model="form.dealtype">
                <el-radio
                  v-for="dict in dealtypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>&ndash;&gt;
            </el-form-item>
          </el-col>-->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size:14px;color: #1890ff;" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button style="width: 80px;height: 30px" type="primary" @click="submitFileForm">确 定</el-button>
        <el-button style="width: 80px;height: 30px" @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import {
        listArea,
        getArea,
        delArea,
        addArea,
        updateArea,
        listAreaExcludeChild,
        changeRiskFlag,
        listAreaByLazyTree
    } from "@/api/sysArea/area";
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    import {getToken} from "@/utils/auth";
    import request from "@/utils/request";

    export default {
        name: "area",
        components: {Treeselect},
      dicts:['risk_type','yes_no'],
        data() {
            return {
                // 遮罩层
                loading: true,
                // 显示搜索条件
                showSearch: true,
                // 表格树数据
                deptList: [],
                // 部门树选项
                deptOptions: [],
                // 部门类型字典
                typeOptions: [],

                dealtypeOptions: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 状态数据字典
                statusOptions: [],
                levelOptions: [],
                // 查询参数
                queryParams: {
                    deptName: undefined,
                    grade: null,
                    status: undefined
                },
                // 表单参数
                form: {},
                upload: {
                    // 是否显示弹出层（用户导入）
                    open: false,
                    // 弹出层标题（用户导入）
                    title: "",
                    // 是否禁用上传
                    isUploading: false,
                    // 是否更新已经存在的用户数据
                    updateSupport: 0,
                    // 设置上传的请求头部
                    headers: {Authorization: "Bearer " + getToken()},
                    // 上传的地址
                    url: process.env.VUE_APP_BASE_API + "/sysArea/area/importData",
                },
                // 表单校验
                rules: {
                    parentId: [
                        {required: true, message: "上级部门不能为空", trigger: "blur"}
                    ],
                    deptName: [
                        {required: true, message: "部门名称不能为空", trigger: "blur"}
                    ],
                    orderNum: [
                        {required: true, message: "显示排序不能为空", trigger: "blur"}
                    ],
                    type: [
                        {required: true, message: "请选择部门类型", trigger: "change"}
                    ],
                    grade: [
                        {required: true, message: "请选择部门级别", trigger: "change"}
                    ],
                    firstchar: [
                        {required: true, message: "请选择部门简拼", trigger: "blur"}
                    ],
                    citycode: [
                        {required: true, message: "请选择部门编码", trigger: "blur"}
                    ],
                    email: [
                        {
                            type: "email",
                            message: "'请输入正确的邮箱地址",
                            trigger: ["blur", "change"]
                        }
                    ],
                    phone: [
                        {
                            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                            message: "请输入正确的手机号码",
                            trigger: "blur"
                        }
                    ]
                }
            };
        },
        created() {
            this.getList();
            /*this.getDicts("sys_normal_disable").then(response => {
                this.statusOptions = response.data;
            });*/
            this.getDictsBatch({
                "area_deal_type": "dealtypeOptions",
            }, this);

            this.getDicts("risk_type").then(response => {
                this.riskTypeOption = response.data;
            });
            this.getDicts("level_type").then(response => {
                this.levelOptions = response.data;
            });
        },
        methods: {
            updateSysAreaCache() {
                let that = this;
                request({
                    url: '/apidata/refreshRedisByKey',
                    method: 'get',
                    params: {
                        'redisKey': "cache:sysarea:all",
                        'redisType': "objectForArea"
                    }
                }).then(response => {
                    that.$modal.msgSuccess(response.msg);
                });
            },
            updateSysAreaByJnfyRiskArea() {
                let that = this;
                request({
                    url: '/sysArea/area/updateSysAreaByJnfyRiskArea',
                    method: 'get',
                }).then(response => {
                    that.$modal.msgSuccess("更新成功!");
                })
            },
            updateReturnInfoRiskByArea() {
                let that = this;
                request({
                    url: '/sysArea/area/updateReturnInfoRiskByArea',
                    method: 'get',
                }).then(response => {
                    that.$modal.msgSuccess("更新成功!");
                })
            },
            handleImport() {
                this.upload.title = "信息导入";
                this.upload.open = true;
            },
            importTemplate() {
                request({
                    url: '/sysArea/area/importTemplate',
                    method: 'get',
                    responseType: 'blob',
                }).then(response => {
                    this.saveBolbAsFile(response, "中高风险地区导入.xlsx");
                })
            },

            load(tree, treeNode, resolve) {
                this.queryParams.grade = "";
                // let listByParent = this.getListByParent(tree.deptId);
                this.queryParams.parentId = tree.deptId;
                listAreaByLazyTree(this.queryParams).then(response => {
                    let sonList = this.handleTree(response.data, "deptId");
                    setTimeout(() => {
                        resolve(sonList)
                    }, 1000)
                });

                // setTimeout(() => {
                //   resolve([
                //     {
                //       id: 31,
                //       date: '2016-05-01',
                //       name: '王小虎',
                //       address: '上海市普陀区金沙江路 1519 弄'
                //     }, {
                //       id: 32,
                //       date: '2016-05-01',
                //       name: '王小虎',
                //       address: '上海市普陀区金沙江路 1519 弄'
                //     }
                //   ])
                // }, 1000)
            },

            handleFileUploadProgress(event, file, fileList) {
                this.upload.isUploading = true;
            },
            // 文件上传成功处理
            handleFileSuccess(response, file, fileList) {
                this.upload.open = false;
                this.upload.isUploading = false;
                this.$refs.upload.clearFiles();
                //  this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
                // this.handleRefresh();

                this.$refs.upload.clearFiles();
                if (response.data.code == "200" && response.data.num == 0) {
                    //this.$alert("导入"+response.data.num+"条!"+response.data.errorText, "导入结果", { dangerouslyUseHTMLString: true });
                    this.$alert(response.data.errorText, "导入结果", {dangerouslyUseHTMLString: true});
                } else {
                    this.$alert("导入完成！", "导入结果", {dangerouslyUseHTMLString: true});
                }

                this.getList();
            },
            // 提交上传文件
            submitFileForm() {
                this.$refs.upload.submit();
            },
            handleStatusChange(row) {
                let text = row.riskflag === "1" ? "中高风险区" : "普通风险区";
                this.$confirm('确认要将当前信息改为' + text + '吗?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    return changeRiskFlag(row.deptId, row.riskflag);
                }).then(() => {
                    this.$modal.msgSuccess("调整成功!");
                }).catch(function () {
                    row.riskflag = row.riskflag === "0" ? "1" : "0";
                });
            },
            /** 查询部门列表 */
            getList() {
                this.loading = true;
                this.queryParams.grade = 1;
                this.queryParams.parentId = "";
                this.deptList = [];
                listAreaByLazyTree(this.queryParams).then(response => {
                    this.deptList = this.handleTree(response.data, "deptId");
                    this.loading = false;
                });
            },
            /** 查询部门列表 */
            getListRload() {
                this.loading = true;
                // this.queryParams.grade = "1"
                // this.queryParams.parentId = "";
                // this.$refs['table'].store.states.lazyTreeNodeMap = {}
                listAreaByLazyTree(this.queryParams).then(response => {
                    // this.deptList = [];
                    let deptList2 = this.handleTree(response.data, "deptId");
                    // this.$refs['table'].store.states.lazyTreeNodeMap = {}
                    this.$set(this.$refs.table.store.states.lazyTreeNodeMap, this.queryParams.parentId, deptList2);
                    this.loading = false;
                });
            },
            getListByParent(parentId) {
                this.loading = true;
                this.queryParams.parentId = parentId;
                listAreaByLazyTree(this.queryParams).then(response => {

                    let sonList = this.handleTree(response.data, "deptId");
                    return sonList;
                });
            },
            /** 转换部门数据结构 */
            normalizer(node) {
                if (node.children && !node.children.length) {
                    delete node.children;
                }
                return {
                    id: node.deptId,
                    label: node.deptName,
                    children: node.children
                };
            },
            // 字典状态字典翻译
            statusFormat(row, column) {
                return this.selectDictLabel(this.statusOptions, row.status);
            },
            dealtypeFormat(row, column) {
                return this.selectDictLabel(this.dealtypeOptions, row.dealtype);
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    deptId: undefined,
                    parentId: undefined,
                    deptName: undefined,
                    orderNum: undefined,
                    leader: undefined,
                    phone: undefined,
                    email: undefined,
                    isDditSon: undefined,
                    status: "0",
                    type: "",
                    grade: "",
                    firstchar: undefined,
                    citycode: undefined

                };
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            /** 新增按钮操作 */
            handleAdd(row) {
                this.reset();
                if (row != undefined) {
                    this.form.parentId = row.deptId;
                    this.form.grade = (parseInt(row.grade) + 1) + "";
                    this.form.orderNum = 1;
                }
                this.open = true;
                this.title = "添加产品/物料";
                listArea().then(response => {
                    this.deptOptions = this.handleTree(response.data, "deptId");
                });
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                getArea(row.deptId).then(response => {
                    this.form = response.data;
                    this.open = true;
                    this.title = "添加产品/物料";
                });
                listAreaExcludeChild(row.deptId).then(response => {
                    this.deptOptions = this.handleTree(response.data, "deptId");
                });
            },
            /** 提交按钮 */
            submitForm: function () {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        if (this.form.deptId != undefined) {
                            updateArea(this.form).then(response => {
                                this.$modal.msgSuccess("修改成功");
                                this.open = false;
                             // this.getList();
                            });
                        } else {
                            addArea(this.form).then(response => {
                                this.$modal.msgSuccess("新增成功");
                                this.open = false;
                                // this.getList();
                            });
                        }
                    }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                this.$confirm('是否确认删除名称为"' + row.deptName + '"的数据项?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    return delArea(row.deptId);
                }).then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
            },
        }
    };
</script>
